package com.apimarket.util.kong.impl;

import com.apimarket.entity.kong.AclCredential;
import com.apimarket.entity.kong.Consumer;
import com.apimarket.entity.kong.Plugin;
import com.apimarket.factory.JsonMapperFactory;
import com.apimarket.util.UrlUtil;
import com.apimarket.util.kong.KongConsumer;
import com.apimarket.util.kong.KongOperationType;
import com.apimarket.util.net.GetNetContext;
import com.apimarket.util.net.NewPostJsonNetContext;
import com.apimarket.util.net.PostJsonNetContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author ZXR
 * @Date 2021/7/9 19:29
 * @Version 1.0
 */

@Component
public class KongConsumerOperation  extends KongConsumer {
    private static final String listPlugin="/plugins";

    public List<Plugin> getConsumerPlugins(String id) throws IOException, URISyntaxException {
        String targetUrl=getBaseUrl()+bindPrefix+"/"+id+listPlugin;
        UrlUtil urlUtil = new UrlUtil(new GetNetContext(targetUrl, null));
        JsonNode root = urlUtil.getJsonRoot();
        root = root.get("data");
        if (root == null) return null;
        ObjectMapper mapper = JsonMapperFactory.getInstance();
        CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Plugin.class);
        return mapper.readValue(root.toString(), listType);
    }
    public Consumer addConsumer(Map<String,Object> params) throws IOException, URISyntaxException {
        String targetUrl=getBaseUrl()+bindPrefix;
        UrlUtil urlUtil = new UrlUtil(new PostJsonNetContext(targetUrl, params));
        JsonNode jsonRoot = urlUtil.getJsonRoot();
        return JsonMapperFactory.getInstance().readValue(jsonRoot.toString(), Consumer.class);
    }

    public Consumer addConsumerAndJudege(Map<String, Object> params) throws IOException, URISyntaxException {
        String targetUrl=getBaseUrl()+bindPrefix;
        NewPostJsonNetContext newPostJsonNetContext = new NewPostJsonNetContext(targetUrl, params);
        JsonNode resultJsonAndJudge = newPostJsonNetContext.getResultJsonAndJudge(KongOperationType.CONSUMER_ADD);
        return JsonMapperFactory.getInstance().readValue(resultJsonAndJudge.toString(), Consumer.class);
    }
}
